package com.jsptpd.smartauth.modules.business.restcontrol;

import com.jsptpd.smartauth.common.util.HashUtils;
import com.jsptpd.smartauth.common.util.StringUtil;
import com.jsptpd.smartauth.modules.business.model.Error;
import com.jsptpd.smartauth.modules.business.model.RespObj;
import com.jsptpd.smartauth.modules.business.model.User;
import com.jsptpd.smartauth.modules.business.service.IUserGsyService;
import com.jsptpd.smartauth.modules.business.service.IUserService;
import com.jsptpd.smartauth.modules.business.utils.Constants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;

    @Autowired
    IUserGsyService userGsyService;


    private Logger log = LoggerFactory.getLogger(UserController.class);

    @ApiOperation(value="获取用户信息-2", notes="兼顾老版本，userId如含有.com，在path里会被去除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "String", paramType = "path"),
    })

    @ResponseBody
    @RequestMapping(value = "/{userId:.+}", method = RequestMethod.GET)
    public RespObj<User> getUserInfo_(@PathVariable String userId) {

        return getUserInfo(userId);
    }

    @ApiOperation(value="获取用户信息-1", notes="")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "String", paramType = "body"),
    })
    @ResponseBody
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public RespObj<User> getUserInfo(@RequestParam String userId) {

        User user = userService.findAllByUserId(userId);
        if (user == null) {
            Error error = new Error(Constants.USER_ERRCODE_INVALID_USER,Constants.USER_ERRMSG_INVALID_USER);
            return new RespObj<User>(error,null);
        } else {
            user.setPassword("");
            return new RespObj<User>(new Error(Constants.USER_ERRCODE_SUCC,""),user);
        }
    }

    @ApiOperation(value="获取用户信息-2", notes="")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", required = false, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "employeeId", value = "内部员工ID", required = false, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "hrId", value = "第三方ID", required = false, dataType = "String", paramType = "body"),
    })
    @ResponseBody
    @RequestMapping(value = "/getInfoById", method = RequestMethod.POST)
    {
        User user = null;
        if(userId!=null && !userId.isEmpty()){
            user = userService.findAllByUserId(userId);
        }else if(employeeId!=null && !employeeId.isEmpty()){
            user = userService.findAllByEmployeeId(employeeId);
        }else if(hrId!=null && !hrId.isEmpty()){
            user = userService.findAllByHrId(hrId);
        }

        if (user == null) {
            Error error = new Error(Constants.USER_ERRCODE_INVALID_USER,Constants.USER_ERRMSG_INVALID_USER);
            return new RespObj<User>(error,null);
        } else {
            user.setPassword("");
            return new RespObj<User>(new Error(Constants.USER_ERRCODE_SUCC,""),user);
        }
    }

    @ApiOperation(value="修改密码-2", notes="后续改成https;兼顾老版本，userId如含有.com，在path里会被去除",consumes="application/x-www-form-urlencoded")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户名", required = true, dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "beforePassword", value = "旧密码", required = true, dataType = "String",paramType = "body"),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true, dataType = "String",paramType = "body")
    })
    @ResponseBody
    @RequestMapping(value = "/modifypassword/{userId:.+}",method = RequestMethod.POST)
    public RespObj<Boolean> modifyPassword_(@PathVariable String userId,
                                           @RequestParam String beforePassword,
                                           @RequestParam String newPassword) {

        return modifyPassword(userId,beforePassword,newPassword);
    }

    @ApiOperation(value="修改密码-1", notes="后续改成https",consumes="application/x-www-form-urlencoded")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户名", required = true, dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "beforePassword", value = "旧密码", required = true, dataType = "String",paramType = "body"),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true, dataType = "String",paramType = "body")
    })
    @ResponseBody
    @RequestMapping(value = "/modPwd",method = RequestMethod.POST)
    public RespObj<Boolean> modifyPassword(@RequestParam String userId,
                                           @RequestParam String beforePassword,
                                           @RequestParam String newPassword) {

        Error error;
        User user = userService.findByUserId(userId);
        if (user == null) {
            error = new Error(Constants.USER_ERRCODE_INVALID_USER,Constants.USER_ERRMSG_INVALID_USER);
            return new RespObj<Boolean>(error,false);
        }
        if (newPassword != null && newPassword.length() < 6) {
            error = new Error(Constants.USER_ERRCODE_INVALID_PWD,Constants.USER_ERRMSG_INVALID_PWD_LEN);
            return new RespObj<Boolean>(error,false);
        }
        if (!StringUtil.equalUpperCase(user.getPassword(), HashUtils.shaPwd(beforePassword))) {
            error = new Error(Constants.USER_ERRCODE_INVALID_PWD,Constants.USER_ERRMSG_INVALID_PWD_OLD);
            return new RespObj<Boolean>(error,false);
        }
        if (newPassword.isEmpty()) {
            error = new Error(Constants.USER_ERRCODE_INVALID_PWD,Constants.USER_ERRMSG_INVALID_PWD_NEW);
            return new RespObj<Boolean>(error,false);
        }

        user.setPassword(HashUtils.shaPwd(newPassword).toUpperCase());
        if(userService.updateUser(user)){
            error = new Error(Constants.USER_ERRCODE_SUCC,Constants.USER_ERRMSG_PWD_SUCC);
        }else{
            error = new Error(Constants.USER_ERRCODE_INVALID_UPDATE,Constants.USER_ERRMSG_INVALID_UPDATE);
        }

        log.info(user.getUserName()+":修改了密码");
        //切换数据库
        try {
            userGsyService.updateByPrimaryKey(user.getUserId(),HashUtils.md5(newPassword).toUpperCase());
        } catch (Exception ex) {
        }

        return new RespObj<Boolean>(error,true);
    }

}
